#/bin/python
#coding:utf8
'''
Created on 2011-5-8

@author: mark
'''

import web
import config
from util import json
from util import auth
from model import problem
from model import answer
from model import choice

tp = config.template_problem

class addchoice:
    def GET(self, pid):
        current_user = web.ctx.session['current_user']
        if not current_user:
            web.seeother('/login') 
        
        pid = int(pid)
        _problem = problem.getproblembyid(pid)
        
        if current_user.uid != _problem.asker:
            return json.write({"msg":"The problem is not yours"})
        
        context = {"problem":_problem}
        return tp.addchoice(context)
    
    def POST(self, pid):
        pid = int(pid)
        i = web.input(desc_a=None, desc_b=None)
        desc_a , desc_b = i['desc_a'], i['desc_b']
        
        cid_a = choice.createchoice(pid, desc_a, "xiaoxiao", 1)
        cid_b = choice.createchoice(pid, desc_b, "yuliang", 2)
        
        return "OK"
    
class answerProblem:
    def POST(self, pid):
        current_user = web.ctx.session['current_user']
        uid = -1 if not current_user else current_user.uid # -1 niming
        
        i = web.input(comment=None)
        cid = i['cid']
        pid = int(pid)
        rank = i['rank']
        
        userip = web.ctx.ip # get ip for the user
           
        aid = answer.createAnswer(pid, cid, uid, userip, rank)
        
        if uid != -1: # not the anonymous user
            problem.addfocutProblem(uid, pid)
            
        return "ok"
    
    def GET(self, pid):
        print "in......"
        current_user = web.ctx.session['current_user']
        uid = -1 if not current_user else current_user.uid # -1 niming
        
        i = web.input(comment=None)
        cid = i['cid']
        pid = int(pid)
        rank = i['rank']
        userip = web.ctx.ip # get ip for the user
        
        #decide whether the problem has been answered by the user 
        _answer = answer.getAnswerByPidAndUid(pid, uid)
        if _answer:
            return "ok"
            
        aid = answer.createAnswer(pid, cid, uid, userip, rank)
        
        if uid != -1: # not the anonymous user
            problem.addfocutProblem(uid, pid)
            
        return "ok"


class checkAnswer:
    def GET(self):
        i = web.input()
        pid = i['pid']
        
        current_user = web.ctx.session['current_user']
        if not current_user:
            return "no answer"
        
        hasanswer = answer.getAnswerByPidAndUid(pid, current_user.uid)
        
        if hasanswer:
            return hasanswer[0].rank
        else:
            return "no answer"
